package com.demo.modules.stock.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class GetResponse {

    protected static final Logger logger = LoggerFactory.getLogger(GetResponse.class);

//    public static String charsetName = "UTF-8";
    public static String charsetName = "GBK";
    public static int connectTimeout = 2000;
    public static int readTimeout = 2000;

    public static void setPara(int connectTimeout, int readTimeout, String charsetName) {
        GetResponse.connectTimeout = connectTimeout;
        GetResponse.readTimeout = readTimeout;
        GetResponse.charsetName = charsetName;
    }

    public static String getResponse(String urlName) {
        logger.info("开始获取返回页面");
        URL url = null;
        URLConnection uc = null;
        InputStream in = null;
        try {
            // 返回一个 URLConnection 对象，它表示到 URL 所引用的远程对象的连接。
            url = new URL(urlName);
            // 打开的连接读取的输入流。
            uc = url.openConnection();
            uc.setConnectTimeout(connectTimeout);
            uc.addRequestProperty("Referer","https://finance.sina.com.cn/");
            uc.setReadTimeout(readTimeout);
            in = uc.getInputStream();
        } catch (Exception e) {
            logger.info("获取页面失败,网络资源不存在或连接超时!");
            e.printStackTrace();
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            return "";
        }
        logger.info("已获取连接:" + urlName);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(in, Charset.forName(charsetName)));
            logger.info("开始读取返回结果");
            // 读取返回结果
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }
            /*
             * int cp; while ((cp = br.read()) != -1) { sb.append((char) cp); }
             */
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info("成功获取返回页面");
        return sb.toString();
    }

}
